// index.js
// 获取应用实例
import env from "../../utils/env";

const app = getApp()

Page({
  data: {
    avatarUrl: app.data.defaultAvatarUrl,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    is_login: false,
    nickName: '',
    list: [
      {
        icon: "/image/aboutUs.png",
        title: "我的订单",
        click: "about"
      },{
        icon: "/image/icons8-qr-code-80.png",
        title: "我的推广码",
        littleTitle: "我的推广码",
        click: "class"
      }, {
        icon: "/image/update.png",
        title: "联系我们",
        click: "contact"
      }, 
      // {
      //   icon: "/image/login.png",
      //   title: "退出登录",
      //   click: "logout"
      // }
    ],
  },
  
  onLoad() {
    if (!this.is_login) {
      this.login();
    } else {
      console.log("is login");
      this.setData({
        nickName: wx.getStorageSync('third_session').substring(0, 10)
      });
      this.getHistoryInfo();
    }
  },
  async getUserProfile(e) {
    const res = await wx.getUserProfile({
      desc: '用于完善会员资料',
    });
    console.log(res);
  },
  globalData: {
    token: null //保存token
  },
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail 
    this.setData({
      avatarUrl,
    })
  },
  
  getUserInfo: function () {
    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (res) => {
        console.log('success');
        this.setData({
          getUserInfo: true,
          userInfo: res.userInfo
        })
      },
      fail: (res) => {
        console.log('fail');
      },
      complete: (res) => {
        console.log('complete');
      },
    })
  },
  //检测是否已经登录
  checkLogin: function (callback) {
    var token = this.globalData.token
    if (!token) {
      //从数据缓存中获取token
      token = wx.getStorageSync('token')
      if (token) {
        this.globalData.token = token;
      } else {
        callback({
          is_login: false
        })
        return
      }
    }
    wx.request({
      url: env.api_host + '/checklogin',
      data: {
        token: token
      },
      success: res => {
        callback({
          is_login: res.data.is_login
        })
      }
    })
  },
  login(e) {
    //调用登录
    let that = this;
    wx.login({
      success: function (res) {
        console.log(res);
        if (res.code) {
          //发起网络请求
          wx.request({
            url: env.api_host + '/auth/miniLogin',
            data: {
              jsCode: res.code
            },
            method: 'POST',
            header: { 'content-type': 'application/json' },
            success: function (data) {
              console.log(data);
              if (data.data.code == 200) {
                wx.setStorageSync('is_login', true);
                wx.setStorageSync('third_session', data.data.data.third_session);
                wx.setStorageSync('access_token', data.data.data.access_token);
                console.log(wx.getStorageSync('third_session'));
                console.log(wx.getStorageSync('access_token'));
                wx.getSetting({
                  success(res) {
                    if (res.authSetting['scope.userInfo']) {
                      // 已经授权，可以直接调用 getUserInfo 获取头像昵称
                      wx.getUserInfo({
                        success(res) {
                          console.log(res);
                          that.setData({
                            is_login: true,
                            nickName: res.userInfo.nickName
                          });
                        }
                      })
                    }
                  }
                })
                that.getHistoryInfo();
              }
            },
            fail: function (data) {
              console.log(data);
            },
            complete: function (data) {
              console.log(data);
            }
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      },
      fail: function () {
        console.log("启用wx.login函数，失败！");
      },
      complete: function () {
        console.log("已启用wx.login函数");
      }
    })
  },
  getHistoryInfo: function () {
    let req = {
      remark: wx.getStorageSync('third_session')
    }
    console.log();
    var that = this;
    wx.request({
      url: env.api_host + '/miniUser/records/list',
      method: 'get',
      header: {
        "content-type": "application/json"
      },
      data: req,
      success(res) {
        console.log("length:", res.data.length);
        for (var i = 0; i < res.data.length; i++) {
          var newarray = {
            createTime: res.data[i].createTime,
            answer: res.data[i].answer,
          };
          that.data.ToDoList = that.data.ToDoList.concat(newarray);
          that.setData({
            ToDoList: that.data.ToDoList
          });
        }
      }
    })
  },
  class(e) {
    wx.navigateTo({
      url: '/pages/myQRCode/index',
    })
  },
  academy(e) {
    console.log(e, "专业");
  },
  about(e) {
    wx.navigateTo({
      url: '/pages/order/index',
    })
  },
  contact(e) {
    console.log("拍摄攻略")
    wx.navigateTo({
      url: '/pages/guide/index',
    })
  },
  logout(e) {
    console.log("退出帐号")
  }
})